const { badRequest, serverError } = require('../utils/response');
const { getLogger } = require('../logger');
const logger = getLogger('middlewares.captchaMemory');
const { verifyCaptcha } = require('../services/captchaService');

// 验证码验证中间件（内存存储｜Redis存储）
const verifyCaptchaMemory = async (req, res, next) => {
    const { captcha, captchaId } = req.body;
    if (!captcha || !captchaId) {
        return badRequest(req, res, '请输入验证码');
    }
    try {
        const { ok, reason } = await verifyCaptcha(captchaId, captcha);
        if (!ok) {
            if (reason === 'not_found') return badRequest(req, res, '验证码不存在，请重新获取');
            if (reason === 'expired') return badRequest(req, res, '验证码已过期，请重新获取');
            if (reason === 'mismatch' || reason === 'missing_params') {
                if (process.env.NODE_ENV === 'development') {
                    logger.info(`[验证码验证] 用户输入: ${captcha}, 验证失败原因: ${reason}`);
                }
                return badRequest(req, res, '验证码错误');
            }
            return badRequest(req, res, '验证码验证失败');
        }
        if (process.env.NODE_ENV === 'development') {
            logger.info(`[验证码验证] 验证成功，验证码ID: ${captchaId}`);
        }
        next();
    } catch (err) {
        logger.error('验证码验证错误:', err);
        serverError(req, res, '验证码验证失败');
    }
};

module.exports = {
    verifyCaptchaMemory
};

